const fs = require('fs');
const path = require('path');
const os = require('os');

// 尝试加载electron的app模块，如果失败则使用fallback
let app;
try {
  const electron = require('electron');
  app = electron.app || global.app;
} catch (error) {
  // 在非Electron环境中使用fallback
  app = global.app || {
    getPath: (name) => {
      if (name === 'userData') {
        return path.join(os.homedir(), 'AppData', 'Roaming', 'flow-system');
      }
      return os.tmpdir();
    }
  };
}

class UnifiedStorage {
  constructor(baseDir = '') {
    this.storagePrefix = 'flow_system_';
    // 确定存储目录
    this.storageDir = path.join(this.getStorageDirectory(), baseDir);
    this.ensureStorageDirectory();

    // 缓存机制
    this.cache = new Map();
    this.cacheTimeout = 5 * 60 * 1000; // 5 minutes cache

    console.log(`Unified storage directory: ${this.storageDir}`);
  }

  // 获取存储目录
  getStorageDirectory() {
    try {
      // 在主进程中使用app.getPath('userData')
      return path.join(app.getPath('userData'), 'storage');
    } catch (error) {
      // 如果在渲染进程或其他环境中，使用临时目录
      const fallbackDir = path.join(os.homedir(), 'AppData', 'Roaming', 'flow-system', 'storage');
      console.warn(`Cannot access app.getPath('userData'), using fallback: ${fallbackDir}`);
      return fallbackDir;
    }
  }

  // 确保存储目录存在
  ensureStorageDirectory() {
    if (!fs.existsSync(this.storageDir)) {
      fs.mkdirSync(this.storageDir, { recursive: true });
    }
  }

  // 获取文件路径
  getFilePath(key) {
    return path.join(this.storageDir, `${this.storagePrefix}${key}.json`);
  }

  // 通用存储方法
  setItem(key, value, useCache = true) {
    try {
      // 确保存储目录存在（每次写入前都检查）
      this.ensureStorageDirectory();

      const filePath = this.getFilePath(key);
      const jsonValue = typeof value === 'string' ? value : JSON.stringify(value);

      fs.writeFileSync(filePath, jsonValue, 'utf8');

      // 更新缓存
      if (useCache) {
        this.cache.set(key, {
          data: value,
          timestamp: Date.now()
        });
      }

      return true;
    } catch (error) {
      console.error(`Error saving data (${key}):`, error);
      return false;
    }
  }

  // 通用获取方法
  getItem(key, useCache = true) {
    try {
      // 先检查缓存
      if (useCache && this.cache.has(key)) {
        const cached = this.cache.get(key);
        if (Date.now() - cached.timestamp < this.cacheTimeout) {
          return cached.data;
        } else {
          this.cache.delete(key);
        }
      }

      const filePath = this.getFilePath(key);
      if (fs.existsSync(filePath)) {
        const data = fs.readFileSync(filePath, 'utf8');

        // 尝试解析JSON，如果失败则返回原始字符串
        let parsedData;
        try {
          parsedData = JSON.parse(data);
        } catch {
          parsedData = data;
        }

        // 更新缓存
        if (useCache) {
          this.cache.set(key, {
            data: parsedData,
            timestamp: Date.now()
          });
        }

        return parsedData;
      }
      return null;
    } catch (error) {
      console.error(`Error reading data (${key}):`, error);
      return null;
    }
  }

  // 通用删除方法
  removeItem(key) {
    try {
      const filePath = this.getFilePath(key);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }

      // 删除缓存
      this.cache.delete(key);
      return true;
    } catch (error) {
      console.error(`Error deleting data (${key}):`, error);
      return false;
    }
  }

  // 清除缓存
  clearCache() {
    this.cache.clear();
  }

  // ==================== 存储初始化方法 ====================

  /**
   * 初始化存储结构和默认数据
   * 在用户登录后调用，确保所有必要的存储文件存在
   */
  initializeStorageStructure() {
    console.log('🔧 [Storage] Initializing storage structure...');

    try {
      // 1. 确保存储目录存在
      this.ensureStorageDirectory();
      console.log('✅ [Storage] Storage directory ensured');

      // 2. 初始化默认应用设置（如果不存在）
      if (!this.getAppSettings()) {
        const defaultSettings = {
          autoLogin: false,
          rememberMe: false,
          language: 'zh-CN',
          theme: 'light',
          lastUpdated: new Date().toISOString()
        };
        this.saveAppSettings(defaultSettings);
        console.log('✅ [Storage] Default app settings created');
      }

      // 3. 初始化空的设备列表（如果不存在）
      if (!this.getDevices()) {
        this.saveDevices([]);
        console.log('✅ [Storage] Empty device list initialized');
      }

      // 4. 初始化空的分组列表（如果不存在）
      if (!this.getDeviceGroups()) {
        this.saveDeviceGroups([]);
        console.log('✅ [Storage] Empty device groups initialized');
      }

      // 5. 初始化默认品牌绑定状态（如果不存在）
      if (!this.getSupportedBrands()) {
        const defaultBrands = {
          'xiaomi': {
            brandName: 'xiaomi',
            isBound: false,
            isExpired: true
          },
          'midea': {
            brandName: 'midea',
            isBound: false,
            isExpired: true
          }
        };
        this.saveSupportedBrands(defaultBrands);
        console.log('✅ [Storage] Default brand bindings initialized');
      }

      // 6. 初始化默认应用状态（如果不存在）
      if (!this.getAppState()) {
        const defaultAppState = {
          isFirstRun: false,
          lastLoginTime: new Date().toISOString(),
          initialized: true
        };
        this.saveAppState(defaultAppState);
        console.log('✅ [Storage] Default app state initialized');
      }

      console.log('✅ [Storage] Storage structure initialization completed');
      return {
        success: true,
        message: 'Storage structure initialized successfully'
      };

    } catch (error) {
      console.error('❌ [Storage] Storage structure initialization failed:', error);
      return {
        success: false,
        message: 'Storage structure initialization failed: ' + error.message
      };
    }
  }

  /**
   * 重新初始化存储（在清空后使用）
   * 用于退出登录后重新登录的场景
   */
  reinitializeAfterCleanup() {
    console.log('🔄 [Storage] Reinitializing storage after cleanup...');

    try {
      // 清除内存缓存
      this.clearCache();

      // 重新初始化存储结构
      const initResult = this.initializeStorageStructure();

      if (initResult.success) {
        console.log('✅ [Storage] Storage reinitialization completed successfully');
        return {
          success: true,
          message: 'Storage successfully reinitialized after cleanup'
        };
      } else {
        return initResult;
      }

    } catch (error) {
      console.error('❌ [Storage] Storage reinitialization failed:', error);
      return {
        success: false,
        message: 'Storage reinitialization failed: ' + error.message
      };
    }
  }

  // ==================== 用户账户相关 ====================

  // 保存用户账户信息
  saveUserAccount(userAccount) {
    if (!userAccount) return false;

    const userData = {
      userId: userAccount.getUserId(),
      lastLoginTime: new Date().toISOString()
    };

    return this.setItem('user', userData);
  }

  // 获取用户账户信息
  getUserAccount() {
    const userData = this.getItem('user');
    if (!userData) return null;

    try {
      // 兼容旧数据
      if (typeof userData === 'string') {
        const parsedData = JSON.parse(userData);
        if (parsedData.username && !parsedData.userId) {
          parsedData.userId = parsedData.username;
        }
        if (!parsedData.userId) return null;
        return { userId: parsedData.userId };
      }

      if (!userData.userId) return null;
      return userData;
    } catch (error) {
      console.error('Error parsing user data:', error);
      return null;
    }
  }

  // 保存令牌
  saveToken(token) {
    if (!token) return false;
    return this.setItem('token', token);
  }

  // 获取令牌
  getToken() {
    return this.getItem('token');
  }

  // 保存刷新令牌
  saveRefreshToken(refreshToken) {
    if (!refreshToken) return false;
    return this.setItem('refresh_token', refreshToken);
  }

  // 获取刷新令牌
  getRefreshToken() {
    return this.getItem('refresh_token');
  }

  // 保存SSE连接ID
  saveSseConnectionId(sseConnectionId) {
    if (!sseConnectionId) return false;
    return this.setItem('sse_connection_id', sseConnectionId);
  }

  // 获取SSE连接ID
  getSseConnectionId() {
    return this.getItem('sse_connection_id');
  }

  // 保存登录凭据
  saveLoginCredentials(userId, rememberMe = false) {
    if (!userId) return false;

    const credentials = {
      userId: userId,
      rememberMe: rememberMe,
      lastLoginTime: new Date().getTime()
    };

    return this.setItem('credentials', credentials);
  }

  // 获取登录凭据
  getLoginCredentials() {
    const credentials = this.getItem('credentials');
    if (!credentials) return null;

    try {
      const now = new Date().getTime();
      const thirtyDays = 30 * 24 * 60 * 60 * 1000;

      if (credentials.rememberMe && (now - credentials.lastLoginTime) < thirtyDays) {
        return credentials;
      } else if (!credentials.rememberMe && (now - credentials.lastLoginTime) < 24 * 60 * 60 * 1000) {
        return credentials;
      }

      this.clearLoginCredentials();
      return null;
    } catch (error) {
      console.error('Error parsing login credentials:', error);
      return null;
    }
  }

  // 清除登录凭据
  clearLoginCredentials() {
    return this.removeItem('credentials');
  }

  // 保存支持的品牌
  saveSupportedBrands(brands) {
    if (!brands) return false;
    return this.setItem('brands', brands);
  }

  // 获取支持的品牌
  getSupportedBrands() {
    const brands = this.getItem('brands');
    return brands || {};
  }

  // 保存应用设置
  saveAppSettings(settings) {
    if (!settings) return false;
    return this.setItem('settings', settings);
  }

  // 获取应用设置
  getAppSettings() {
    const settings = this.getItem('settings');
    return settings || { autoLogin: false, rememberMe: false };
  }

  // ==================== 设备相关 ====================

  // 保存设备列表
  saveDevices(devices) {
    if (!devices) return false;

    const deviceData = {
      devices: devices,
      lastUpdated: new Date().toISOString(),
      count: devices.length
    };

    return this.setItem('devices', deviceData);
  }

  // 获取设备列表
  getDevices() {
    const deviceData = this.getItem('devices');
    if (!deviceData) return null;

    return deviceData.devices || [];
  }

  // 获取设备最后更新时间
  getDevicesLastUpdated() {
    const deviceData = this.getItem('devices');
    return deviceData ? deviceData.lastUpdated : null;
  }

  // 保存特定设备状态
  saveDeviceState(deviceId, state) {
    if (!deviceId || !state) return false;

    const stateData = {
      ...state,
      lastUpdated: new Date().toISOString()
    };

    return this.setItem(`device_${deviceId}`, stateData);
  }

  // 获取特定设备状态
  getDeviceState(deviceId) {
    if (!deviceId) return null;
    return this.getItem(`device_${deviceId}`);
  }

  // ==================== 应用状态相关 ====================

  // 保存应用状态
  saveAppState(state) {
    if (!state) return false;

    const appState = {
      ...state,
      lastUpdated: new Date().toISOString()
    };

    return this.setItem('app_state', appState);
  }

  // 获取应用状态
  getAppState() {
    const state = this.getItem('app_state');
    return state || {};
  }

  // 保存页面状态
  savePageState(pageName, state) {
    if (!pageName || !state) return false;

    const pageState = {
      ...state,
      lastUpdated: new Date().toISOString()
    };

    return this.setItem(`page_${pageName}`, pageState);
  }

  // 获取页面状态
  getPageState(pageName) {
    if (!pageName) return null;
    return this.getItem(`page_${pageName}`);
  }

  // ==================== 传感器数据相关 ====================

  // 保存传感器历史数据
  saveSensorHistory(deviceId, historyData) {
    if (!deviceId || !historyData) return false;

    // 支持两种调用方式：
    // 1. saveSensorHistory(deviceId, historyDataArray) - 新格式
    // 2. saveSensorHistory(deviceId, metricType, data) - 旧格式（兼容性）
    let dataToSave;

    if (Array.isArray(historyData)) {
      // 新格式：直接保存历史数据数组
      dataToSave = {
        deviceId,
        data: historyData,
        lastUpdated: new Date().toISOString(),
        format: 'array'
      };
    } else if (typeof historyData === 'string') {
      // 旧格式兼容：第二个参数是metricType，第三个参数是data
      const metricType = historyData;
      const data = arguments[2];
      dataToSave = {
        deviceId,
        metricType,
        data,
        lastUpdated: new Date().toISOString(),
        format: 'metric'
      };
      return this.setItem(`sensor_${deviceId}_${metricType}`, dataToSave);
    } else {
      return false;
    }

    return this.setItem(`sensor_history_${deviceId}`, dataToSave);
  }

  // 获取传感器历史数据
  getSensorHistory(deviceId, metricTypeOrMode = 'all') {
    if (!deviceId) return null;

    // 如果metricTypeOrMode是'all'，返回完整的历史数据数组
    if (metricTypeOrMode === 'all') {
      const historyData = this.getItem(`sensor_history_${deviceId}`);
      if (historyData && historyData.data && Array.isArray(historyData.data)) {
        return historyData.data;
      }
      return null;
    }

    // 否则按照旧格式查找特定指标的数据（兼容性）
    const specificData = this.getItem(`sensor_${deviceId}_${metricTypeOrMode}`);
    if (specificData && specificData.data) {
      return specificData.data;
    }

    return null;
  }

  // ==================== 数据清理相关 ====================

  // 清除用户数据
  clearUserData() {
    this.removeItem('user');
    this.removeItem('token');
    this.removeItem('refresh_token');
    this.removeItem('sse_connection_id');
    this.removeItem('brands');
    this.clearLoginCredentials();
    return true;
  }

  // 清除设备数据
  clearDeviceData() {
    this.removeItem('devices');
    // 清除所有单个设备状态
    const files = fs.readdirSync(this.storageDir);
    files.forEach(file => {
      if (file.startsWith(`${this.storagePrefix}device_`) && file.endsWith('.json')) {
        const filePath = path.join(this.storageDir, file);
        fs.unlinkSync(filePath);
      }
    });
    return true;
  }

  // 清除传感器数据
  clearSensorData() {
    const files = fs.readdirSync(this.storageDir);
    files.forEach(file => {
      if (file.startsWith(`${this.storagePrefix}sensor_`) && file.endsWith('.json')) {
        const filePath = path.join(this.storageDir, file);
        fs.unlinkSync(filePath);
      }
    });
    return true;
  }

  // ==================== 设备分组相关 ====================

  // 保存设备分组数据
  saveDeviceGroups(groups) {
    if (!groups || !Array.isArray(groups)) return false;

    const groupData = {
      groups: groups,
      lastUpdated: new Date().toISOString(),
      count: groups.length
    };

    return this.setItem('device_groups', groupData);
  }

  // 获取设备分组数据
  getDeviceGroups() {
    const groupData = this.getItem('device_groups');
    if (!groupData) return [];

    try {
      // 兼容性处理
      if (Array.isArray(groupData)) {
        return groupData;
      }

      if (groupData.groups && Array.isArray(groupData.groups)) {
        return groupData.groups;
      }

      return [];
    } catch (error) {
      console.error('Error parsing device group data:', error);
      return [];
    }
  }

  // 获取设备分组最后更新时间
  getDeviceGroupsLastUpdated() {
    const groupData = this.getItem('device_groups');
    return groupData && groupData.lastUpdated ? groupData.lastUpdated : null;
  }

  // 保存单个设备分组
  saveDeviceGroup(groupId, groupData) {
    if (!groupId || !groupData) return false;
    return this.setItem(`device_group_${groupId}`, groupData);
  }

  // 获取单个设备分组
  getDeviceGroup(groupId) {
    if (!groupId) return null;
    return this.getItem(`device_group_${groupId}`);
  }

  // 删除设备分组数据
  clearDeviceGroups() {
    try {
      // 删除主分组文件
      this.removeItem('device_groups');

      // 删除所有单个分组文件
      const files = fs.readdirSync(this.storageDir);
      const groupFiles = files.filter(file =>
        file.startsWith(`${this.storagePrefix}device_group_`) && file.endsWith('.json')
      );

      groupFiles.forEach(file => {
        fs.unlinkSync(path.join(this.storageDir, file));
      });

      console.log('Device group data cleared');
      return true;
    } catch (error) {
      console.error('Error clearing device group data:', error);
      return false;
    }
  }

  // 清除所有数据
  clearAllData() {
    console.log('🗑️ [Storage] Starting clearAllData...');

    try {
      // 基础数据清理
      this.clearUserData();
      this.clearDeviceData();
      this.clearSensorData();
      this.clearDeviceGroups();
      this.removeItem('app_state');

      if (!fs.existsSync(this.storageDir)) {
        console.log('🗑️ [Storage] Storage directory does not exist');
        return true;
      }

      // 清除所有页面状态和其他文件
      const files = fs.readdirSync(this.storageDir);
      let deletedCount = 0;

      files.forEach(file => {
        try {
          if (file.startsWith(this.storagePrefix) && file.endsWith('.json')) {
            const filePath = path.join(this.storageDir, file);
            fs.unlinkSync(filePath);
            deletedCount++;
            console.log(`🗑️ [Storage] Deleted: ${file}`);
          }
        } catch (error) {
          console.error(`🗑️ [Storage] Failed to delete ${file}:`, error.message);
        }
      });

      console.log(`🗑️ [Storage] clearAllData completed: ${deletedCount} files deleted`);
      this.clearCache();
      return true;

    } catch (error) {
      console.error('🗑️ [Storage] clearAllData failed:', error);
      return false;
    }
  }

  // 彻底清除整个存储目录（登出时使用）
  async clearDeviceGroupData() {
    // 示例：这里可以添加具体的清除逻辑
    // 例如，删除特定的JSON文件或数据库表
    console.log('Device group data cleared');
  }

  // 彻底清除所有数据和文件（登出时使用）
  clearAllDataCompletely() {
    console.log('🔥 [STORAGE DEBUG] =======================================');
    console.log('🔥 [STORAGE DEBUG] Starting complete data cleanup...');
    console.log('🔥 [STORAGE DEBUG] Storage directory path:', this.storageDir);
    console.log('🔥 [STORAGE DEBUG] Process working directory:', process.cwd());
    console.log('🔥 [STORAGE DEBUG] Process platform:', process.platform);
    console.log('🔥 [STORAGE DEBUG] =======================================');

    const result = {
      success: false,
      deletedFiles: 0,
      failedFiles: 0,
      deletedDirectories: 0,
      message: '',
      details: []
    };

    try {
      // 检查存储目录是否存在
      console.log('🔥 [STORAGE DEBUG] Checking if storage directory exists...');
      const dirExists = fs.existsSync(this.storageDir);
      console.log('🔥 [STORAGE DEBUG] Storage directory exists:', dirExists);

      if (!dirExists) {
        console.log('🔥 [STORAGE DEBUG] ⚠️ Storage directory does not exist, nothing to clean');
        result.success = true;
        result.message = 'Storage directory does not exist, nothing to clean';
        return result;
      }

      console.log(`🔥 [STORAGE DEBUG] ✅ Storage directory found: ${this.storageDir}`);

      // 清除内存缓存
      console.log('🔥 [STORAGE DEBUG] Clearing memory cache...');
      this.clearCache();
      console.log('🔥 [STORAGE DEBUG] ✅ Memory cache cleared');

      // 获取所有文件和目录
      console.log('🔥 [STORAGE DEBUG] Reading directory contents...');
      let items;
      try {
        items = fs.readdirSync(this.storageDir);
        console.log(`🔥 [STORAGE DEBUG] Found ${items.length} items to process:`, items);
      } catch (error) {
        console.error('🔥 [STORAGE DEBUG] ❌ Failed to read directory:', error);
        result.success = false;
        result.message = `Failed to read storage directory: ${error.message}`;
        result.details.push(`Failed to read directory: ${error.message}`);
        return result;
      }

      // 删除所有文件和子目录
      console.log('🔥 [STORAGE DEBUG] Starting to delete items...');
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        const itemPath = path.join(this.storageDir, item);
        console.log(`🔥 [STORAGE DEBUG] Processing item ${i+1}/${items.length}: ${item}`);
        console.log(`🔥 [STORAGE DEBUG] Full path: ${itemPath}`);

        try {
          const stats = fs.statSync(itemPath);
          console.log(`🔥 [STORAGE DEBUG] Item stats: isDirectory=${stats.isDirectory()}, size=${stats.size}`);

          if (stats.isDirectory()) {
            console.log(`🔥 [STORAGE DEBUG] Deleting directory: ${item}`);
            // 递归删除目录
            fs.rmSync(itemPath, { recursive: true, force: true });
            result.deletedDirectories++;
            result.details.push(`Deleted directory: ${item}`);
            console.log(`🔥 [STORAGE DEBUG] ✅ Deleted directory: ${item}`);
          } else {
            console.log(`🔥 [STORAGE DEBUG] Deleting file: ${item}`);
            // 删除文件
            fs.unlinkSync(itemPath);
            result.deletedFiles++;
            result.details.push(`Deleted file: ${item}`);
            console.log(`🔥 [STORAGE DEBUG] ✅ Deleted file: ${item}`);
          }
        } catch (error) {
          result.failedFiles++;
          result.details.push(`Failed to delete ${item}: ${error.message}`);
          console.error(`🔥 [STORAGE DEBUG] ❌ Failed to delete ${item}:`, error.message);
          console.error(`🔥 [STORAGE DEBUG] Error details:`, error);
        }
      }

      // 尝试删除空的存储目录
      console.log('🔥 [STORAGE DEBUG] Checking if storage directory can be deleted...');
      try {
        const remainingItems = fs.readdirSync(this.storageDir);
        console.log(`🔥 [STORAGE DEBUG] Remaining items in directory: ${remainingItems.length}`, remainingItems);

        if (remainingItems.length === 0) {
          console.log('🔥 [STORAGE DEBUG] Directory is empty, deleting...');
          fs.rmdirSync(this.storageDir);
          result.deletedDirectories++;
          result.details.push('Deleted empty storage directory');
          console.log('🔥 [STORAGE DEBUG] ✅ Deleted empty storage directory');
        } else {
          console.log(`🔥 [STORAGE DEBUG] ⚠️ Storage directory still contains ${remainingItems.length} items, keeping directory`);
          result.details.push(`Storage directory still contains ${remainingItems.length} items`);
        }
      } catch (error) {
        console.error('🔥 [STORAGE DEBUG] ❌ Failed to delete storage directory:', error.message);
        console.error('🔥 [STORAGE DEBUG] Error details:', error);
        result.details.push(`Failed to delete storage directory: ${error.message}`);
      }

      // 验证删除结果
      console.log('🔥 [STORAGE DEBUG] Verifying cleanup results...');
      const stillExists = fs.existsSync(this.storageDir);
      console.log('🔥 [STORAGE DEBUG] Storage directory still exists after cleanup:', stillExists);

      if (stillExists) {
        try {
          const finalItems = fs.readdirSync(this.storageDir);
          console.log('🔥 [STORAGE DEBUG] Final directory contents:', finalItems);
        } catch (error) {
          console.log('🔥 [STORAGE DEBUG] Cannot read directory after cleanup (likely deleted)');
        }
      }

      result.success = result.failedFiles === 0 || result.deletedFiles > 0;
      result.message = `Cleanup completed: ${result.deletedFiles} files and ${result.deletedDirectories} directories deleted, ${result.failedFiles} failed`;

      console.log('🔥 [STORAGE DEBUG] =======================================');
      console.log(`🔥 [STORAGE DEBUG] Cleanup summary: ${result.message}`);
      console.log('🔥 [STORAGE DEBUG] Detailed results:', result);
      console.log('🔥 [STORAGE DEBUG] =======================================');

      return result;

    } catch (error) {
      console.error('🔥 [STORAGE DEBUG] ❌ Complete cleanup failed:', error);
      console.error('🔥 [STORAGE DEBUG] Error stack:', error.stack);
      result.success = false;
      result.message = `Complete cleanup failed: ${error.message}`;
      result.details.push(`Critical error: ${error.message}`);
      return result;
    }
  }

  /**
   * @returns {Promise<void>}
   */
  async cleanupStorage() {
    console.log(`Starting to completely clean up storage directory: ${this.storageDir}`);
    if (fs.existsSync(this.storageDir)) {
      try {
        const files = fs.readdirSync(this.storageDir);
        let deletedCount = 0;
        let failedCount = 0;

        for (const file of files) {
          const filePath = path.join(this.storageDir, file);
          try {
            if (fs.statSync(filePath).isDirectory()) {
              // 递归删除子目录
              fs.rmdirSync(filePath, { recursive: true });
              console.log(`Deleted directory: ${file}`);
            } else {
              fs.unlinkSync(filePath);
              console.log(`Deleted file: ${file}`);
            }
            deletedCount++;
          } catch (error) {
            // console.error(`Failed to delete ${filePath}:`, error.message);
            failedCount++;
          }
        }
        console.log(`File cleanup complete: ${deletedCount} deleted successfully, ${failedCount} failed`);

        // 检查目录是否为空
        const remainingFiles = fs.readdirSync(this.storageDir);
        if (remainingFiles.length === 0) {
          fs.rmdirSync(this.storageDir);
          console.log('Storage directory deleted');
        } else {
          console.log(`Storage directory still has ${remainingFiles.length} files, keeping directory`);
        }
      } catch (error) {
        console.log('Failed to delete storage directory or it does not exist:', error.message);
      }
    } else {
      console.log('Storage directory does not exist, no cleanup needed');
    }
  }

  // ==================== 工具方法 ====================

  // 检查是否有有效的登录状态
  hasValidSession() {
    const userAccount = this.getUserAccount();
    const credentials = this.getLoginCredentials();
    const refreshToken = this.getRefreshToken();

    return !!(userAccount && credentials && refreshToken);
  }

  // 获取存储统计信息
  getStorageStats() {
    const stats = {
      totalFiles: 0,
      totalSize: 0,
      categories: {
        user: 0,
        devices: 0,
        sensors: 0,
        pages: 0,
        other: 0
      }
    };

    try {
      const files = fs.readdirSync(this.storageDir);

      files.forEach(file => {
        if (file.startsWith(this.storagePrefix) && file.endsWith('.json')) {
          stats.totalFiles++;

          const filePath = path.join(this.storageDir, file);
          const stat = fs.statSync(filePath);
          stats.totalSize += stat.size;

          // 分类统计
          if (file.includes('user') || file.includes('token') || file.includes('credentials')) {
            stats.categories.user++;
          } else if (file.includes('device')) {
            stats.categories.devices++;
          } else if (file.includes('sensor')) {
            stats.categories.sensors++;
          } else if (file.includes('page_')) {
            stats.categories.pages++;
          } else {
            stats.categories.other++;
          }
        }
      });
    } catch (error) {
      console.error('Error getting storage stats:', error);
    }

    return stats;
  }

  // 导出数据
  exportData() {
    const data = {};

    try {
      const files = fs.readdirSync(this.storageDir);

      files.forEach(file => {
        if (file.startsWith(this.storagePrefix) && file.endsWith('.json')) {
          const key = file.replace(this.storagePrefix, '').replace('.json', '');
          const filePath = path.join(this.storageDir, file);
          const content = fs.readFileSync(filePath, 'utf8');

          try {
            data[key] = JSON.parse(content);
          } catch {
            data[key] = content;
          }
        }
      });
    } catch (error) {
      console.error('Error exporting data:', error);
    }

    return data;
  }

  // 导入数据
  importData(data) {
    if (!data || typeof data !== 'object') return false;

    try {
      Object.keys(data).forEach(key => {
        this.setItem(key, data[key], false); // 不使用缓存
      });

      this.clearCache(); // 清除缓存以强制重新读取
      return true;
    } catch (error) {
      console.error('Error importing data:', error);
      return false;
    }
  }
}

module.exports = UnifiedStorage;
